<template>
  <div>
    {{ ruleForm.type }}
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="商品分类" prop="type">
        <!-- <el-input v-model="ruleForm.type" /> -->

        <el-cascader placeholder="商品分类" :props="props" v-model="ruleForm.type" />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="商品简介" prop="desc">
        <el-input v-model="ruleForm.desc" type="textarea" />
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input min="0" v-model="ruleForm.price" type="number" />
      </el-form-item>
      <el-form-item label="售卖价格" prop="salesprice">
        <el-input min="0" v-model="ruleForm.salesprice" type="number" />
      </el-form-item>
      <el-form-item label="库存" prop="store">
        <el-input min="0" v-model="ruleForm.store" type="number" />
      </el-form-item>

      <el-form-item label="商品标签" prop="flag">
        <el-input v-model="ruleForm.flag" />
      </el-form-item>

      <el-form-item label="上架状态" prop="resource">
        <el-radio-group v-model="ruleForm.resource">
          <el-radio value="1">上架</el-radio>
          <el-radio value="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上传图片" prop="imageUrl">
        <el-upload
          class="avatar-uploader"
          action="http://backend-api-02.newbee.ltd/manage-api/v1/upload/file"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :headers="{ Token }"
        >
          <img
            v-if="ruleForm.imageUrl"
            :src="ruleForm.imageUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="详情内容" prop="content">
        <editorVue
          :content="ruleForm.content"
          :readOnlys="readOnlys"
          @changeData="hChangeData"
          @uploadImg="hUploadImg"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          立即创建
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
 
<script setup>
let Token = localStorage.getItem("token");
import { Plus } from "@element-plus/icons-vue";
import { ref, reactive } from "vue";
import editorVue from "../../components/editorVue.vue";
import axios from "../../ajax";
let readOnlys = ref(false);
import {useRouter} from "vue-router"
const router=useRouter()
const hChangeData = (editDataHtml) => {
  ruleForm.content = editDataHtml;
};
const hUploadImg =async (file, insertFn) => {
  let formDatas=new FormData();
  formDatas.append("file",file)
  // formDatas.append("a",100)

   let res=await axios.post("/upload/files",formDatas,{
    headers:{//请求头部
      "Content-Type":"application/x-www-form-urlencoded"// 表单格式
      // "Content-Type":"application/json"  //json默认格式
    }
   })
 
  insertFn(res[0]);
};
// 以上是富文本编辑器********************************************
// 下面是分类的代码

const props = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level, value } = node;
    // console.log(node);
    let { list } = await axios.get("/categories", {
      params: {
        pageNumber: 1,
        pageSize: 1000,
        categoryLevel: level + 1,
        parentId: level == 0 ? 0 : value, //**** */
      },
    });
    const nodes = [
      // {
      //   value: 0, // id
      //   level: level + 1,
      //   label: `分类 - ${0}`, //名字
      //   leaf: level >= 2,
      // },
    ];

    list.map((item) => {
      nodes.push({
        value: item.categoryId, // id
        label: item.categoryName, //名字
        leaf: level >= 2,
      });
    });

    // console.log(nodes);
    resolve(nodes);
  },
};

// 表面的数据****************************
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  type: "", //分类
  name: "", //名称
  desc: "", //商品简介
  price: "", //商品价格
  salesprice: "", //商品售卖价格
  store: "", //库存
  flag: "", //商品标签
  imageUrl: "",

  resource: "1", //上架下架状态
  content: "", //富文本编辑器数据
});
const rules = reactive({
  type: [{ required: true, message: "输入分类名称", trigger: "blur" }],
  name: [{ required: true, message: "输入商品名称", trigger: "blur" }],
  desc: [{ required: true, message: "商品简介", trigger: "blur" }],
  price: [{ required: true, message: "商品价格", trigger: "blur" }],
  salesprice: [{ required: true, message: "售卖价格", trigger: "blur" }],
  store: [{ required: true, message: "库存不能为空", trigger: "blur" }],
  flag: [{ required: true, message: "商品标签", trigger: "blur" }],
  resource: [
    {
      required: true,
      message: "选择上架状态",
      trigger: "change",
    },
  ],
  imageUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
  // content:[
  // { required: true, message: '请输入详情内容', trigger: 'blur' },

  // ]
});

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      /// ajax
      addGoods()
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

const addGoods = async () => {//******************添加商品******* */
  let res = await axios.post("/goods", {
    goodsCategoryId: ruleForm.type[2],
    goodsCoverImg:ruleForm.imageUrl,
    goodsDetailContent: ruleForm.content,
    goodsIntro: ruleForm.desc,
    goodsName: ruleForm.name,
    goodsSellStatus:ruleForm.resource,
    originalPrice: ruleForm.price,
    sellingPrice: ruleForm.salesprice,
    stockNum: ruleForm.store,
    tag: ruleForm.flag,
  });
  router.push({
      name:"Category",
      query:{
        categoryLevel:1,
        parentId:0
      }
  })
};

// 图片的上传效果

// 图片上传

// const imageUrl = ref('')

const beforeAvatarUpload = (rawFile) => {
  // 图片大小验证
  console.log(rawFile.type);
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png"
  ) {
    return true;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  } else {
    ElMessage.error("图片格式不正确!");
    return false;
  }
  // return true
};
const handleAvatarSuccess = (
  //上传成功
  response,
  uploadFile
) => {
  ruleForm.imageUrl = response.data;
};
</script>

<style lang="scss">
.avatar-uploader {
  width: 100px;
  height: 100px;
  line-height: 100px;
  border: 1px dashed #999;
  text-align: center;
  font-size: 50px;
  color: #999;
  &:hover {
    border: 1px dashed red;
    color: red;
  }
  img {
    width: 100%;
    height: 100px;
  }
}
</style>
